package com.yikes.srb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.constant.hfb.FormHelper;
import com.yikes.srb.constant.hfb.HfbConst;
import com.yikes.srb.constant.hfb.RequestHelper;
import com.yikes.srb.leadingModle.form.lendItem.InvestForm;
import com.yikes.srb.leadingModle.form.lendItem.LendItemAddForm;
import com.yikes.srb.leadingModle.form.lendItem.LendItemEditForm;
import com.yikes.srb.leadingModle.form.lendItem.LendItemQuery;
import com.yikes.srb.leadingModle.vo.LendItemVO;
import com.yikes.srb.mapper.UserAccountMapper;
import com.yikes.srb.pojo.bo.TransFlowBO;
import com.yikes.srb.pojo.entity.Lend;
import com.yikes.srb.pojo.entity.LendItem;
import com.yikes.srb.mapper.LendItemMapper;
import com.yikes.srb.pojo.enums.LendStatusEnum;
import com.yikes.srb.pojo.enums.ServiceWorkCodeEnum;
import com.yikes.srb.pojo.enums.TransTypeEnum;
import com.yikes.srb.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.util.LendNoUtils;
import com.yikes.srb.web.utils.As;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LendItemServiceImpl extends ServiceImpl<LendItemMapper, LendItem> implements LendItemService {

    private final LendService lendService;

    private final UserAccountService userAccountService;

    private final UserAccountMapper userAccountMapper;

    private final UserBindService userBindService;

    private final TransFlowService transFlowService;

    @Override
    public PageResult<LendItemVO> listPage(LendItemQuery query) {

        Page<LendItem> page = lambdaQuery()
                .like(StrUtil.isNotBlank(query.getLendItemNo()), LendItem::getLendItemNo, query.getLendItemNo())
                .eq(ObjectUtil.isNotNull(query.getLendId()), LendItem::getLendId, query.getLendId())
                .eq(ObjectUtil.isNotNull(query.getInvestUserId()), LendItem::getInvestUserId, query.getInvestUserId())
                .like(StrUtil.isNotBlank(query.getInvestName()), LendItem::getInvestName, query.getInvestName())
                .eq(ObjectUtil.isNotNull(query.getInvestAmount()), LendItem::getInvestAmount, query.getInvestAmount())
                .ge(ObjectUtil.isNotNull(query.getLendStartDate()), LendItem::getLendStartDate, query.getLendStartDate())
                .le(ObjectUtil.isNotNull(query.getLendEndDate()), LendItem::getLendEndDate, query.getLendEndDate())
                .eq(ObjectUtil.isNotNull(query.getStatus()), LendItem::getStatus, query.getStatus())
                .page(Page.of(query.getPageNum(), query.getPageSize()));

        List<LendItemVO> bean = BeanUtils.toBean(page.getRecords(), LendItemVO.class);
        return PageResult.build(page.getTotal(), page.getPages(), bean);
    }

    @Override
    public LendItemVO infoId(Long id) {

        LendItem lendItem = getById(id);
        LendItemVO bean = BeanUtils.toBean(lendItem, LendItemVO.class);
        return bean;
    }

    @Override
    public void create(LendItemAddForm form) {

        LendItem bean = BeanUtils.toBean(form, LendItem.class);
        save(bean);
    }

    @Override
    public void edit(LendItemEditForm form) {

        LendItem bean = BeanUtils.toBean(form, LendItem.class);
        updateById(bean);
    }

    @Override
    public void del(Long id) {

        baseMapper.deleteById(id);
    }

    @Override
    public String commitInvest(InvestForm form) {


        //输入校验==========================================
        Long lendId = form.getLendId();
        //获取标的信息
        Lend lend = lendService.getById(lendId);

        //标的状态必须为募资中
        As.isTure(
                lend.getStatus().intValue() == LendStatusEnum.INVEST_RUN.getStatus().intValue(),
                ServiceWorkCodeEnum.LEND_INVEST_ERROR);

        //标的不能超卖：(已投金额 + 本次投资金额 )>=标的金额（超卖）
        BigDecimal sum = lend.getInvestAmount().add(new BigDecimal(form.getInvestAmount()));
        As.isTure(sum.doubleValue() <= lend.getAmount().doubleValue(),
                ServiceWorkCodeEnum.LEND_FULL_SCALE_ERROR);

        //账户可用余额充足：当前用户的余额 >= 当前用户的投资金额（可以投资）
        Long investUserId = form.getInvestUserId();
        //获取当前用户的账户余额
        BigDecimal amount = userAccountService.getAccount(investUserId);
        As.isTure(amount.doubleValue() >= Double.parseDouble(form.getInvestAmount()),
                ServiceWorkCodeEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        //在商户平台中生成投资信息==========================================
        //标的下的投资信息
        LendItem lendItem = new LendItem();
        lendItem.setInvestUserId(investUserId);//投资人id
        lendItem.setInvestName(form.getInvestName());//投资人名字
        String lendItemNo = LendNoUtils.getLendItemNo();
        lendItem.setLendItemNo(lendItemNo); //投资条目编号（一个Lend对应一个或多个LendItem）
        lendItem.setLendId(form.getLendId());//对应的标的id
        lendItem.setInvestAmount(new BigDecimal(form.getInvestAmount())); //此笔投资金额
        lendItem.setLendYearRate(lend.getLendYearRate());//年化
        lendItem.setInvestTime(LocalDateTime.now()); //投资时间
        lendItem.setLendStartDate(lend.getLendStartDate()); //开始时间
        lendItem.setLendEndDate(lend.getLendEndDate()); //结束时间

        //预期收益
        BigDecimal expectAmount = lendService.getInterestCount(
                lendItem.getInvestAmount(),
                lendItem.getLendYearRate(),
                lend.getPeriod(),
                lend.getReturnMethod());
        lendItem.setExpectAmount(expectAmount);

        //实际收益
        lendItem.setRealAmount(new BigDecimal(0));

        lendItem.setStatus(0);//默认状态：刚刚创建
        baseMapper.insert(lendItem);


        //组装投资相关的参数，提交到汇付宝资金托管平台==========================================
        //在托管平台同步用户的投资信息，修改用户的账户资金信息==========================================
        //获取投资人的绑定协议号
        String bindCode = userBindService.getBindCodeByUserId(investUserId);
        //获取借款人的绑定协议号
        String benefitBindCode = userBindService.getBindCodeByUserId(lend.getUserId());

        //封装提交至汇付宝的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("voteBindCode", bindCode);
        paramMap.put("benefitBindCode", benefitBindCode);
        paramMap.put("agentProjectCode", lend.getLendNo());//项目标号
        paramMap.put("agentProjectName", lend.getTitle());

        //在资金托管平台上的投资订单的唯一编号，要和lendItemNo保持一致。
        paramMap.put("agentBillNo", lendItemNo);//订单编号
        paramMap.put("voteAmt", form.getInvestAmount());
        paramMap.put("votePrizeAmt", "0");
        paramMap.put("voteFeeAmt", "0");
        paramMap.put("projectAmt", lend.getAmount()); //标的总金额
        paramMap.put("note", "");
        paramMap.put("notifyUrl", HfbConst.INVEST_NOTIFY_URL); //检查常量是否正确
        paramMap.put("returnUrl", HfbConst.INVEST_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建充值自动提交表单
        return FormHelper.buildForm(HfbConst.INVEST_URL, paramMap);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notify(Map<String, Object> paramMap) {
        log.info("投标成功");

        //获取投资编号
        String agentBillNo = (String) paramMap.get("agentBillNo");

        boolean result = transFlowService.isSaveTransFlow(agentBillNo);
        if (result) {
            log.warn("幂等性返回");
            return;
        }

        //获取用户的绑定协议号
        String bindCode = (String) paramMap.get("voteBindCode");
        String voteAmt = (String) paramMap.get("voteAmt");

        //修改商户系统中的用户账户金额：余额、冻结金额
        userAccountMapper.updateAccount(bindCode, new BigDecimal("-" + voteAmt), new BigDecimal(voteAmt));

        //修改投资记录的投资状态改为已支付
        LendItem lendItem = this.getByLendItemNo(agentBillNo);
        lendItem.setStatus(1);//已支付
        baseMapper.updateById(lendItem);

        //修改标的信息：投资人数、已投金额
        Long lendId = lendItem.getLendId();
        Lend lend = lendService.getById(lendId);
        lend.setInvestNum(lend.getInvestNum() + 1);
        lend.setInvestAmount(lend.getInvestAmount().add(lendItem.getInvestAmount()));
        lendService.updateById(lend);

        //新增交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(voteAmt),
                TransTypeEnum.INVEST_LOCK,
                "投资项目编号：" + lend.getLendNo() + "，项目名称：" + lend.getTitle());
        transFlowService.saveTransFlow(transFlowBO);

    }

    @Override
    public List<LendItemVO> selectByLendId(Long lendId) {

        List<LendItem> list = lambdaQuery().eq(LendItem::getLendId, lendId).list();
        return BeanUtils.toBean(list, LendItemVO.class);
    }

    @Override
    public List<LendItem> selectByLendIds(Long lendId, int status) {

        return lambdaQuery().eq(LendItem::getLendId, lendId).eq(LendItem::getStatus, status).list();
    }

    private LendItem getByLendItemNo(String agentBillNo) {

        LendItem lendItem = lambdaQuery().eq(LendItem::getLendItemNo, agentBillNo).one();
        return lendItem;
    }
}
